import { getCityAll } from '@/api/web/city'

function storageBuilder (type) {
  const storage = window[type]
  return {
    setString: storage.setItem,
    getString: storage.getItem,
    setNumber (key, number) {
      storage.setItem(key, (number || '').replace(/[^\d]/g, ''))
    },
    getNumber (key) {
      return Number(storage.getItem(key))
    },
    setBoolean (key, boolean) {
      storage.setItem(key, !!boolean)
    },
    getBoolean (key) {
      return storage.getItem(key) === 'true'
    },
    setObject (key, object) {
      storage.setItem(key, JSON.stringify(object))
    },
    getObject (key) {
      return JSON.parse(storage.getItem(key))
    },
    removeItem (key) {
      storage.removeItem(key)
    }
  }
}

const localStorage = storageBuilder('localStorage')

const city = {
  state: {
    cityAll: localStorage.getObject('cityAll') || []
  },

  mutations: {
    SET_cityAll: (state, data) => {
      state.cityAll = data
      localStorage.setObject('cityAll', data)
    }
  },

  actions: {
    // 所有区域
    GetCityAll({ commit }) {
      return new Promise((resolve, reject) => {
        getCityAll().then(response => {
            console.log(response.data)
            commit('SET_cityAll', response.data)
            resolve(response)
        }).catch(error => {
            reject(error)
        })
      })
    }

  }
}

export default city
